package com.object.oriented.exam.system6.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.object.oriented.exam.system1.dao.KnowledgeMapping;
import com.object.oriented.exam.system1.entity.Knowledge;
import com.object.oriented.exam.system1.entity.Problem;
import com.object.oriented.exam.system1.entity.Result;
import com.object.oriented.exam.system1.service.ProblemService;
import com.object.oriented.exam.system5.entity.Answer;
import com.object.oriented.exam.system5.entity.Exam;
import com.object.oriented.exam.system5.entity.Score;
import com.object.oriented.exam.system5.mapper.AnswerMapper;
import com.object.oriented.exam.system5.mapper.ExamMapper;
import com.object.oriented.exam.system5.mapper.ScoreMapper;
import com.object.oriented.exam.system5.service.AnswerService;
import com.object.oriented.exam.system6.entity.Student;
import com.object.oriented.exam.system6.entity.dto.ErrorKnowledge;
import com.object.oriented.exam.system6.entity.dto.ExamScore;
import com.object.oriented.exam.system6.entity.dto.StudentExamScoreVo;
import com.object.oriented.exam.system6.mapper.StudentMapper;
import com.object.oriented.exam.system6.service.StudentManageService;
import com.object.oriented.exam.system8.entity.Question;
import com.object.oriented.exam.system8.service.QuestionService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author huangjiajun
 * @date 2023.06.19 20:19
 **/

@Service
public class StudentManageServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentManageService {

    @Resource
    StudentMapper studentMapper;
    @Resource
    ScoreMapper scoreMapper;
    @Resource
    ExamMapper examMapper;

    @Resource
    AnswerMapper answerMapper;

    @Resource
    ProblemService problemService;

    @Resource
    KnowledgeMapping knowledgeMapping;

    @Override
    public Result listStudent() {
        List<Student> students = studentMapper.selectList(new QueryWrapper<>());
        return Result.success(students);
    }

    @Override
    @Transactional
    public Result insert(Student student) {
        int res = studentMapper.insert(student);
//        if (res == 0){
//            Result.fail("更新失败;");
//        }
        return Result.success();
    }

    @Override
    @Transactional
    public Result update(Student student) {
        int res = studentMapper.updateById(student);
//        if (res == 0){
//            return Result.fa("更新失败;");
//        }
        return Result.success();
    }

    @Override
    public Result delete(Student student) {
        int res = studentMapper.deleteById(student);

        return Result.success();
    }

    @Override
    public Result listStudentExamScore(int studentId) {


        // 查询 score 表
        QueryWrapper<Score> queryWrapper = new QueryWrapper<Score>().select("total_score","exam_id").eq("student_id", studentId);
        List<Score> scoreList = scoreMapper.selectList(queryWrapper);

        if(scoreList.isEmpty()){
            return Result.success();
        }

        // 波动
        int minScore = Integer.MAX_VALUE;
        int maxScore = Integer.MIN_VALUE;
        int sumScore = 0;
        int avgScore = 0;

        List<ExamScore> examScoreList = new ArrayList<>();
        // 再查出 exam 表
        for (Score score : scoreList) {
            Exam exam = examMapper.selectById(score.getExamId());
            ExamScore examScore = new ExamScore();
            examScore.setTotalScore(score.getTotalScore());
            examScore.setSubject(exam.getSubject());
            examScore.setDate(exam.getDate());

            examScoreList.add(examScore);

            // 波动计算
            minScore = Math.min(minScore,score.getTotalScore());
            maxScore = Math.max(maxScore,score.getTotalScore());
            sumScore += score.getTotalScore();
        }
        avgScore = sumScore/scoreList.size();

        return Result.success(new StudentExamScoreVo(examScoreList,avgScore,minScore,maxScore));
    }

    @Override
    public Result errKnowledgeAnalyze(int studentId) {

        QueryWrapper<Answer> answerQueryWrapper =new QueryWrapper<>();
        answerQueryWrapper
                .eq("student_id",studentId)
                .eq("result",1);

        // 获取错题
        List<Answer> wrongAnswerList = answerMapper.selectList(answerQueryWrapper);

        List<ErrorKnowledge> errorKnowledgeList =new LinkedList<>();
        // 用于去重
        HashMap<String,ErrorKnowledge> errorKnowledgeNameMap = new HashMap<>();


        // 根据错题，获取题目相关信息（答案，解析等）
        for(Answer answer:wrongAnswerList){
            Question question =new Question();

            question.setProblemId(answer.getQuestionId());
            question.setResult(answer.getAnswer());

            // 查询题目难度
            Problem problem= problemService.getById(answer.getQuestionId());
            if(problem!=null){
                // 查询知识点
                Knowledge knowledge= knowledgeMapping.selectById(problem.getKnowledgeId());
                if(knowledge!=null){
                    if(errorKnowledgeNameMap.containsKey(knowledge.getTitle())){
                        ErrorKnowledge errorKnowledge = errorKnowledgeNameMap.get(knowledge.getTitle());
                        // 频次加一
                        errorKnowledge.setFrequency(errorKnowledge.getFrequency()+1);
                    }else{
                        ErrorKnowledge errorKnowledge = new ErrorKnowledge();
                        errorKnowledge.setKnowLedgeName(knowledge.getTitle());
                        errorKnowledge.setDifficulty(problem.getDifficulty());
                        // 频次初始化为1
                        errorKnowledge.setFrequency(1);
                        errorKnowledgeList.add(errorKnowledge);
                        // 加入 map，用于去重
                        errorKnowledgeNameMap.put(knowledge.getTitle(),errorKnowledge);
                    }
                }
            }
        }

        return Result.success(errorKnowledgeList);
    }

}
